package com.kainitram.drivebook.data_adapters;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.List;

import com.kainitram.drivebook.R;
import com.kainitram.drivebook.models.Car;
import com.kainitram.library.BaseArrayAdapter;
import com.kainitram.library.BaseViewWrapper;
import com.kainitram.library.ViewWrapper;

import android.content.Context;
import android.view.View;
import android.widget.TextView;

/**
 * Data adapter for car entity
 * 
 * @author Mino
 * 
 */
public class CarsAdapter extends BaseArrayAdapter<Car> {

	private DecimalFormat decimalFormat;

	public CarsAdapter(Context context, List<Car> objects) {
		super(context, R.layout.car_item, objects);

		DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
		symbols.setGroupingSeparator(' ');
		decimalFormat = new DecimalFormat("###,###.## ", symbols);
	}

	@Override
	protected void onBindViewToItem(Car item, ViewWrapper viewWrapper,
			Boolean isPortrait) {
		CarViewWrapper wrapper = (CarViewWrapper) viewWrapper;

		wrapper.setEvc(item.getEvc());
		wrapper.setTach(decimalFormat.format(item.getTachometerState()));

		if (!isPortrait) {
			wrapper.setAvgConsuption(decimalFormat.format(item
					.getAverageConsumption()));
			wrapper.setTotalCoast(decimalFormat.format(item.getTotalCoast()));
		}

	}

	@Override
	protected BaseViewWrapper createViewWrapperForRowView(View rowView) {
		return new CarViewWrapper(rowView);
	}

	class CarViewWrapper extends BaseViewWrapper {
		private View baseView;
		private TextView tvSPZ;
		private TextView tvTach;
		private TextView tvAvgConsuption;
		private TextView tvTotalCoast;

		public CarViewWrapper(View baseView) {
			this.baseView = baseView;
		}

		public TextView getTvEVC() {
			if (tvSPZ == null) {
				tvSPZ = (TextView) baseView.findViewById(R.id.tvItemSPZ);
			}

			return tvSPZ;
		}

		public TextView getTvTach() {
			if (tvTach == null) {
				tvTach = (TextView) baseView.findViewById(R.id.tvItemTACH);
			}
			return tvTach;
		}

		public TextView getAvgConsuption() {
			if (tvAvgConsuption == null) {
				tvAvgConsuption = (TextView) baseView
						.findViewById(R.id.tvAvgConsuption);
			}

			return tvAvgConsuption;
		}

		public TextView getTotalCoast() {
			if (tvTotalCoast == null) {
				tvTotalCoast = (TextView) baseView
						.findViewById(R.id.tvTotalCoast);
			}

			return tvTotalCoast;
		}

		public void setEvc(String evc) {
			getTvEVC().setText(evc);
		}

		public void setTach(String tachValue) {
			getTvTach().setText(tachValue);
		}

		public void setAvgConsuption(String avgConsuption) {
			getAvgConsuption().setText(avgConsuption);
		}

		public void setTotalCoast(String totalCoast) {
			getTotalCoast().setText(totalCoast);
		}
	}
}